package com.tjetc.config;

import com.tjetc.interceptor.UserInterceptor;
import com.tjetc.pojo.po.UserPo;
import com.tjetc.pojo.request.UserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author gaoyongxiang
 * @version v1.0
 * @since 2025-10-10
 *
 * 我们平时在写的时候，springboot给我们提供的转换器基本满足我们的需求
 */
@Configuration
public class WebConfig implements WebMvcConfigurer{

    @Autowired
    private UserInterceptor userInterceptor;

//    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            // 添加新的类型转换器
            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter<String, UserRequest>() {
                    // source就是前端发送过来的请求数据
                    @Override
                    public UserRequest convert(String source) {
                        System.out.println("source = " + source);
                        // zhangsan,1
                        String[] split = source.split(",");
                        UserRequest userRequest = new UserRequest();
                        userRequest.setName(split[0]);
                        userRequest.setAge(Integer.valueOf(split[1]));
                        return userRequest;
                    }
                });
            }
        };
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截器的配置规则
       registry.addInterceptor(userInterceptor)
               // 添加要拦截的请求路径
               .addPathPatterns("/**")
               // 排除哪些请求路径
               .excludePathPatterns("/login");
    }
}
